package com.example.lcpharmacy.service;

import com.example.lcpharmacy.entity.CartEntity;
import com.example.lcpharmacy.entity.resBean.ShowCartInfo;
import com.example.lcpharmacy.lcutils.StringUtils;
import com.example.lcpharmacy.mapper.CartDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

@Service
public class CartService {

    @Autowired
    private CartDao cartDao;

    public List<ShowCartInfo> queryCart(String userName){
        List<ShowCartInfo> showCartInfos = cartDao.selectByName(userName);
        return showCartInfos;
    }

    public int insertCart(CartEntity cartEntity){
        CartEntity existBean = cartDao.queryByGoodCode(cartEntity);
        if(Objects.nonNull(existBean)){
            return 0;
        }
        Integer cartCode = createCartCode();
        cartEntity.setCartCode(cartCode);
        int i = cartDao.addCart(cartEntity);
        return i;
    }

    public Integer createCartCode() {
        Integer cartCode = 0;
        Integer maxCartCode = cartDao.selectMaxCartCode();
        if (StringUtils.isEmpty(maxCartCode)) {
            // 初始值
            cartCode = 10001;
        } else {
            cartCode = maxCartCode + 1;
        }
        return cartCode;
    }

    public int subGoodCount(CartEntity cartEntity){
        //验证数量大于等于1
        BigDecimal currQuan = cartDao.selectQuanByCode(cartEntity.getCartCode());
        BigDecimal comItem = new BigDecimal(1);
        if(currQuan.compareTo(comItem)==1){
            int i = cartDao.subGoodsQuan(cartEntity);
            return i;
        }
        return 0;
    }
}
